<template>
  <a-modal
    :open="open"
    width="640px"
    :title="rowData?.bsdh ? '修改报损单' : '新增报损单'"
    centered
    :ok-button-props="{ disabled: !isCompleted }"
    ok-text="保存"
    @ok="onOk"
    @cancel="onCancel"
  >
    <a-form :model="formState" class="form-style-flex">
      <a-form-item v-if="formState.bsdh" label="报损单号">
        <a-input v-model:value="formState.bsdh" disabled placeholder="" />
      </a-form-item>
      <a-form-item label="报损仓库" class="w-1/2" v-bind="validateInfos.ckmc">
        <SelectWarehouse v-model:value="formState.ckmc" @select="onSelectSupplier" />
      </a-form-item>
      <a-form-item label="制单人" class="w-1/2">
        {{ formState.jhr }}
      </a-form-item>
      <a-form-item label="备注" class="w-full">
        <a-textarea v-model:value="formState.cmemo" :rows="6" placeholder="请输入" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script setup>
import { ref, watchEffect } from 'vue'
import { message } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import SelectWarehouse from '@/components/SelectWarehouse'

import useUserStore from '@/store/user'
import { post } from '@/utils/request'

const { empName } = useUserStore()

const router = useRouter()
const emit = defineEmits(['update:open', 'ok'])
const props = defineProps({
  open: {
    type: Boolean,
    default: false
  },
  rowData: {
    type: Object,
    default: () => ({})
  }
})
const formState = ref({
  ckmc: '',
  cmemo: '',
  jhr: empName
})
const rulesState = ref({
  ckmc: [{ required: true, message: '请选择报损仓库' }]
})
const { isCompleted, resetFields, validate, validateInfos } = useForm(formState, rulesState)
watchEffect(() => {
  if (props.open) {
    formState.value = { jhr: empName, ...props.rowData }
  }
})
const onCancel = () => {
  emit('update:open', false)
  resetFields()
}
const onOk = async () => {
  await validate()
  const params = {
    bsdh: formState.value.bsdh ?? '',
    ckbh: formState.value?.ckbh,
    ckmc: formState.value?.ckmc,
    cmemo: formState.value?.cmemo
  }
  const { code, msg, data } = await post('/oos/psiform/doSaveLossOverflowHead', params)
  if (code === 0) {
    message.success('保存成功')
    router.push({
      path: '/optic-warehouse/warehouse/loss-detail',
      query: {
        bsdh: data.bsdh
      }
    })
    onCancel()
    emit('ok')
    return
  }
  message.error(msg)
}
const onSelectSupplier = (_, supplier) => {
  formState.value.ckbh = supplier?.ckid
  formState.value.ckmc = supplier?.ckmc
}
</script>
<style lang="less" scoped></style>
